using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Reflection;
using System.Threading;

namespace GPSou
{
    public partial class FormTransfer : Form
    {
        delegate void InfoMsg(String texto);
        delegate void BarraProgreso(int valor);
        delegate void Salir(System.Windows.Forms.DialogResult result);

        public string usuario;
        public string clave;

        Thread t = null;
        ManualResetEvent m_EventStopThread = new ManualResetEvent(false);
        ManualResetEvent m_EventThreadStopped = new ManualResetEvent(false);

        public FormTransfer()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (t == null)
            {
                m_EventThreadStopped.Reset();
                m_EventStopThread.Reset();

                ThreadStart ts = new ThreadStart(transferir);
                t = new Thread(ts);
                t.Start();
            }
        }

        private void transferir()
        {
            string respuesta = "";

            string appFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            string dataFileStr = Path.Combine(appFolder, "datos.txt");

            try
            {
                long size;

                String auth = "p=login&login=" + usuario + "&password=" + clave + "&datos=";
                byte[] authBytes = Encoding.UTF8.GetBytes(auth);
                FileStream fileStream = new FileStream(dataFileStr, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                size = fileStream.Length;

                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://SERVER/GoogleGPS/ServletGoogleGPS");
                httpReq.Method = "POST";
                httpReq.ContentType = "application/x-www-form-urlencoded";
                httpReq.ContentLength = authBytes.Length + size;

                Stream writeStream = httpReq.GetRequestStream();

                writeStream.Write(authBytes, 0, authBytes.Length);

                byte[] b = new byte[200];
                long i = 0;
                int l;
                while ((i < size) && !m_EventStopThread.WaitOne(0, false))
                {
                    l = fileStream.Read(b, 0, 200);
                    writeStream.Write(b, 0, l);
                    i += l;

                    barraProgreso((int)(100 * i / size));
                }

                infoMsg("PROCESANDO DATOS...");

                writeStream.Close();
                fileStream.Close();

                if (!m_EventStopThread.WaitOne(0, false))
                {
                    HttpWebResponse webResp = (HttpWebResponse)httpReq.GetResponse();
                    Stream receiveStream = webResp.GetResponseStream();
                    StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                    respuesta = readStream.ReadToEnd();

                    webResp.Close();
                }
                else
                    httpReq.Abort();

            }
            catch (Exception) { }

            if (respuesta.CompareTo("OK") == 0)
            {
                File.Delete(dataFileStr);
                File.Create(dataFileStr).Close();
                salir(System.Windows.Forms.DialogResult.OK);
            }
            else
                salir(System.Windows.Forms.DialogResult.Retry);

            m_EventThreadStopped.Set();
            t = null;
        }

        void barraProgreso(int valor)
        {
            if (InvokeRequired)
            {
                Invoke(new BarraProgreso(barraProgreso), new object[] { valor });
            }
            else
            {
                progressBar.Value = valor;
            }
        }

        void infoMsg(String texto)
        {
            if (InvokeRequired)
            {
                Invoke(new InfoMsg(infoMsg), new object[] { texto });
            }
            else
            {
                buttonCancel.Enabled = false;
                labelProcesando.Text = texto;
            }
        }

        void salir(System.Windows.Forms.DialogResult result)
        {
            if (InvokeRequired)
            {
                Invoke(new Salir(salir), new object[] { result });
            }
            else
                DialogResult = result;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (t != null)
            {
                m_EventStopThread.Set();
                while (!m_EventThreadStopped.WaitOne(0, false))
                    Application.DoEvents();
            }
            else
            {
                salir(System.Windows.Forms.DialogResult.Cancel);
            }
        }

        private void FormTransfer_Activated(object sender, EventArgs e)
        {
            buttonCancel.Enabled = true;
            labelProcesando.Text = "";
        }

    }
}
